<template>
  <div class="search-result-container">
    <div class="header">
      <div class="header-1">
        <img src="../../public/images/返回.png" alt="返回" @click="goBack" class="back" />
        <div class="ssk">
          <img src="../../public/images/放大镜.png" alt="" class="fdj" @click="goBack" />
          <input type="text" v-model="searchQuery" disabled class="ssk-1" @click="goBack" />
          <img src="../../public/images/回车.png" alt="" class="fdj" @click="goBack" />
        </div>
        <RouterLink to="/shoppingcar"><img src="../../public/images/购物车.png" alt="" class="gwc"></RouterLink
        >
      </div>
      <div class="xian"></div>
      <!-- 新增按钮容器 -->
      <div class="button-group">
        <button @click="sortBy('pop')" :class="{ 'active-button': activeSort === 'pop' }">
          综合
        </button>
        <button @click="sortBy('sell')" :class="{ 'active-button': activeSort === 'sell' }">
          销量
        </button>
        <button @click="sortBy('new')" :class="{ 'active-button': activeSort === 'new' }">
          新品
        </button>
        <button @click="togglePriceDropdown">
          价格
          <img src="../../public/images/下拉.png" alt="" class="xiala" />
        </button>
        <!-- 新增价格下拉框容器 -->
        <div class="price-dropdown" v-show="showPriceDropdown">
          <!-- 循环生成价格区间按钮 -->
          <div class="price-btn">
            <div
              v-for="(filter, index) in priceFilterData"
              :key="index"
              class="price-filter"
              @click="sortByPriceFilter(filter.min, filter.max)"
            >
              <span>{{ filter.min }} - {{ filter.max }}</span>
            </div>
          </div>
          <div class="price-range">
            <span>区间(元)</span>
            <input type="text" v-model="priceMin" />
            <span>-</span>
            <input type="text" v-model="priceMax" />
            <button @click="sortByPriceRange">确认</button>
          </div>
        </div>
      </div>
    </div>

    <div>
      <!-- 新增一个包裹商品列表的容器 -->
      <div v-if="loading" class="jiazai"></div>
      <div v-else-if="searchResults.length > 0" class="product-list">
        <!-- 商品列表 -->
        <div
          v-for="item in searchResults"
          :key="item.tradeItemId"
          class="product-item"
          @click="goToItemDetail(item.tradeItemId)"
        >
          <!-- 商品图片 -->
          <van-image width="100%" height="240rem" fit="cover" :src="item.img" />
          <!-- 商品信息 -->
          <div class="product-info">
            <p class="product-name">{{ item.title }}</p>
            <p class="product-price">¥{{ item.price }}</p>
            <p class="product-sales">
              {{ item.cfav }} <img src="../../public/images/收藏.png" alt="" class="sc" />
            </p>
          </div>
        </div>
      </div>
      <div v-else class="product-nosome">
        <div>
          <img src="../../public/images/无商品.png" alt="" class="no-some" />
        </div>
        <span>没有相关的商品结果哦~~</span>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { createApp } from 'vue'
import { Image as VanImage } from 'vant'

const app = createApp()
app.use(VanImage)

interface SearchResultItem {
  tradeItemId: string
  img: string
  title: string
  price: number
  cfav: number
}

interface PriceFilter {
  max: string
  min: string
  percent: string
}

export default defineComponent({
  props: {
    q: String,
  },
  setup(props) {
    const router = useRouter()
    const route = useRoute()
    const searchQuery = ref(props.q || '')
    const loading = ref(false)
    const searchResults = ref<SearchResultItem[]>([])
    const isSearchBoxDisabled = ref(false)
    const activeSort = ref('') // 用于记录当前亮起按钮对应的排序参数
    const showPriceDropdown = ref(false) // 用于控制价格下拉框的显示与隐藏
    const priceFilterData = ref<PriceFilter[]>([]) // 新增，用于存储价格区间数据
    const priceMin = ref('')
    const priceMax = ref('')
    const sortParam = ref('')

    if (route.query.isDisabled) {
      isSearchBoxDisabled.value = true
    }

    const fetchSearchResults = async () => {
      loading.value = true
      let url = `https://apis.netstart.cn/mogujie/search/searchByKeyword?q=${searchQuery.value}`
      // 根据排序参数拼接
      if (sortParam.value) {
        url += `&${sortParam.value}`
      }
      // 这里可以根据实际情况添加其他参数的赋值与拼接，如页码、排序等

      try {
        const response = await fetch(url)
        const data = await response.json()
        const results = data.result.wall.docs.map((doc: any) => ({
          tradeItemId: doc.tradeItemId,
          img: doc.img,
          title: doc.title,
          price: doc.price,
          cfav: doc.cfav,
        }))
        searchResults.value = results

        // 提取priceFilter数据赋值给priceFilterData响应式数据
        priceFilterData.value = data.result.priceFilter
      } catch (error) {
        console.error('请求搜索商品出现错误：', error)
      } finally {
        loading.value = false
      }
    }

    const sortBy = (param: string) => {
      activeSort.value = param
      sortParam.value = `sort=${param}`
      fetchSearchResults()
    }

    const sortByPriceRange = () => {
      const min = priceMin.value.trim()
      const max = priceMax.value.trim()
      if (!/^\d+$/.test(min) || !/^\d+$/.test(max)) {
        // 简单验证是否为纯数字
        console.error('输入的价格不是有效的数字，请重新输入')
        return
      }
      if (Number(min) > Number(max)) {
        console.error('最小价格不能大于最大价格，请重新输入')
        return
      }
      if (priceMin.value && priceMax.value) {
        sortParam.value = `minPrice=${priceMin.value}&maxPrice=${priceMax.value}`
        // `minPrice=${min}&maxPrice=${max}`
        console.log(`sortParam: ${sortParam.value}`)
      }

      showPriceDropdown.value = false
      fetchSearchResults()
    }

    const sortByPriceFilter = (min: string, max: string) => {
      sortParam.value = `minPrice=${min}&maxPrice=${max}`
      showPriceDropdown.value = false
      fetchSearchResults()
    }

    const togglePriceDropdown = () => {
      showPriceDropdown.value = !showPriceDropdown.value
    }

    onMounted(() => {
      if (route.query.q) {
        searchQuery.value = route.query.q as string
        fetchSearchResults()
      }
    })

    const goBack = () => {
      router.back()
    }
    const goToItemDetail = (iid: string) => {
      router.push({ name: 'TiaoZhuan', params: { iid: iid } })
      console.log('商品详情页的iid:', iid)
    }

    return {
      searchQuery,
      searchResults,
      goBack,
      fetchSearchResults,
      loading,
      isSearchBoxDisabled,
      sortBy,
      sortByPriceRange,
      sortParam,
      activeSort,
      showPriceDropdown,
      priceFilterData,
      priceMin,
      priceMax,
      togglePriceDropdown,
      sortByPriceFilter,
      goToItemDetail,
    }
  },
})
</script>

<style scoped>
.header {
  width: 100%;
  height: 80rem;
  /* 固定在上方 */
  position: fixed;
  top: 0;
  z-index: 1000;
  background-color: white;
  border-bottom: 1px solid #e5e5e5;
}

.header-1 {
  display: flex;
  justify-content: space-between;
  font-size: 16rem;
  height: 40rem;
}

.xian {
  width: 100%;
  height: 1px;
  background-color: #99999949;
  margin: 0;
}

.back {
  width: 17rem;
  height: 17rem;
  margin-top: 10rem;
  margin-left: 10rem;
}

.ssk {
  margin: 0 auto;
  border: 1px #aaa;
  width: 78%;
  height: 30rem;
  color: #000000;
  font-size: 16rem;
  background-color: #ececec;
  margin-top: 5rem;
}

.fdj {
  width: 16rem;
  height: 16rem;
  float: left;
  margin-top: 8rem;
  margin-left: 3rem;
}

.gwc {
  width: 20rem;
  height: 20rem;
  float: right;
  margin-top: 10rem;
  margin-right: 14rem;
}

.ssk-1 {
  width: 77%;
  height: 24rem;
  color: #000000;
  font-size: 16rem;
  padding: 0rem 20rem;
  background-color: #ececec;
  border: none;
  outline: none;
  /* 上下居中 */
  margin-top: 2rem;
}

.jiazai {
  font-size: 20rem;
  margin: 10rem auto;
}

.product-list {
  width: 100%;
  /* height: 10000rem; */
  background-color: #ececec;
  margin: 0;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-evenly;
  margin-top: 81rem;
}

.product-item {
  display: block;
  width: 47%;
  /* float: left; */
  margin: 2% 0;
  background-color: white;
  border: 1rem solid #f5f5f5;
  border-radius: 5rem;
}

.product-image {
  width: 100%;
  height: auto;
}

.van-image {
  border-top-right-radius: 5rem;
  border-top-left-radius: 5rem;
}

.product-info {
  text-align: center;
}

.product-name {
  font-size: 12rem;
  color: #333;
  text-align: left;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  text-overflow: ellipsis;
  overflow: hidden;
  line-height: 20rem;
  margin: 5rem 3rem;
}

.product-price {
  font-size: 16rem;
  margin: 0;
  float: left;
  font-weight: 700;
  color: #333;
  overflow: hidden;
  margin-left: 9rem;
}

.product-sales {
  font-size: 12rem;
  color: #999;
  margin: 0;
  float: right;
  margin-right: 10rem;
}

.sc {
  width: 15rem;
  height: 15rem;
  float: right;
  margin-top: -2rem;
  margin-right: 0rem;
}

.button-group {
  display: flex;
  justify-content: space-around;
  margin: 10rem 0;
}

.button-group button {
  width: 25%;
  border: none;
  padding: 2rem 10rem;
  font-size: 14rem;
  color: #333;
  background-color: white;
  cursor: pointer;
  transition: background-color 0.3s ease;
  border-left: 1rem solid #dfdfdf;
}

.button-group button:hover {
  color: #ef4562;
}

.active-button {
  background-color: red;
}

/* 价格下拉框容器样式 */
.price-dropdown {
  position: absolute;
  top: 80rem;
  /* 根据实际情况调整位置，使其在价格按钮下方合适位置显示 */
  background-color: white;
  border: 1px solid #ccc;
  padding: 5rem;
  z-index: 10;
  width: 100%;
  box-sizing: border-box;
}

/* 价格下拉框内价格区间按钮样式 */
.price-filter {
  font-size: 14rem;
  color: #333;
  background-color: #f3f3f3;
  text-align: center;
  height: 25rem;
  width: 30%;
  /* 字体上下居中 */
  line-height: 25rem;
}

.price-btn {
  display: flex;
  justify-content: space-between;
  width: 95%;
  margin: 0 auto;
}

.price-filter:hover {
  background-color: #f0f0f0;
}

.price-filter:last-child {
  margin-bottom: 0;
}

/* 价格下拉框内自定义价格区间输入框样式 */
.price-range {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10rem;
  font-size: 14rem;
}

.price-range span {
  font-size: 14rem;
}

.price-range input {
  border: 1px solid #e5e5e5;
  padding: 2rem 10rem;
  font-size: 14rem;
  color: #333;
  background-color: white;
  width: 50rem;
  font-size: 16rem;
}

.price-range button {
  border: none;
  border-radius: 0rem;
  padding: 2rem 10rem;
  font-size: 14rem;
  color: white;
  background-color: #ff5b76;
  width: 80rem;
  text-align: center;
  transition: background-color 0.3s ease;
}

.price-range button:hover {
  background-color: #e67787;
}

.no-some {
  width: 30%;
  height: auto;
  margin: 16rem auto;
}

.product-nosome {
  width: 100%;
  height: 1000rem;
  text-align: center;
  background-color: #ececec;
  margin-top: 81rem;
}

.product-nosome span {
  width: 100%;
  height: 100%;
  font-size: 15rem;
  color: #888;
}

.xiala {
  width: 23rem;
  height: 23rem;
  position: absolute;
}
</style>
